package com.sgj.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.sgj.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Calendar;

/**
 * @Author: Guoji Shen
 * @Date: 2021/12/14 15:09
 */
@Slf4j
@Component
public class JWTUtils {

    private static String U_ID = "userId";
    private static String U_NAME = "username";
    private static String SIGN;

    @Value("${jwt.token.sign}")
    public void setSign(String sign) {
        SIGN = sign;
    }

    /**
     * 生成 token
     * @param user
     * @return
     */
    public static String getToken(User user) {
        // 默认1天token过期
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, 1);

        String token = JWT.create()
                // head 有默认值，可以不写
                // .withHeader(map)
                // payload
                .withClaim(U_ID, user.getId())
                .withClaim(U_NAME, user.getUsername())
                // 过期时间
                .withExpiresAt(instance.getTime())
                // 签名
                .sign(Algorithm.HMAC256(SIGN));
        log.info("[JWTUtils][getToken] token:{}", token);
        return token;
    }

    /**
     * 验证 token
     * @param token
     */
    public static DecodedJWT verify(String token) {
        return JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
    }

    /**
     * 获取用户id
     * @param token
     * @return
     */
    public static String getUserId(String token) {
        return verify(token).getClaim(U_ID).toString();
    }

    /**
     * 获取用户名
     * @param token
     * @return
     */
    public static String getUsername(String token) {
        return verify(token).getClaim(U_NAME).toString();
    }
}